package servlet.XMLTree;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import offer.GetDataSource;
import offer.GetNodeFromModule;

import com.netscenery.yang.model.*;
import com.netscenery.yang.model.Enum;


public class ValidateNodeServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ValidateNodeServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out
				.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("    This is ");
		out.print(this.getClass());
		out.println(", using the GET method");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/xml; charset=utf-8");
		request.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control","no-cache"); 
		PrintWriter  out = response.getWriter();
		String nodeLevel = request.getParameter("nodeLevel");
		String[]  levers =  nodeLevel.split("\\\\");
		Module    module = GetDataSource.getDataRead(request);
		Object   curNode = null;                             //��¼��ǰ�Ҽ����ڽ��
		curNode = GetNodeFromModule.getItemNode(module,levers);  //��ȡ��ǰ�Ҽ����ڽ��
		ArrayList<ValidateInfo> resultList =new ArrayList<ValidateInfo>();
		ValidateOfElement(curNode,resultList);
		
		GetDataSource.getDataWrite(request, module);
		StringBuilder xmlData      = new StringBuilder();
		xmlData.append("<?xml version='1.0' encoding='UTF-8'?>");
		xmlData.append("<validate>");
		xmlData.append("<length>"+resultList.size()+"</length>");
		for(int i = 0 ; i < resultList.size() ; i++){
			ValidateInfo tempInfo = resultList.get(i);
	        xmlData.append("<validateResult>");
			xmlData.append("<Result>false</Result>");
			xmlData.append("<Severity>"+tempInfo.getSeverity()+"</Severity>");
			xmlData.append("<Reason>"+tempInfo.getReason()+"</Reason>");
			xmlData.append("<NodeIdStr>"+tempInfo.getNodeIdStr()+"</NodeIdStr>");
	        xmlData.append("</validateResult>");
		}
		xmlData.append("</validate>");
		out.write(xmlData.toString());
		out.flush();
		out.close();
	}
	
	private boolean ValidateOfElement(Object nodeIntem , ArrayList<ValidateInfo> resultList){
		boolean validateResult = false;
		Method validateMethod = null;
		Validator validator =null;
		try {
			validateMethod = nodeIntem.getClass().getMethod("validate");//ģ�������нڵ㶼ʵ����validate����
			validator= (Validator)validateMethod.invoke(nodeIntem);
			validateResult = validator.isValid();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		
		for(int i = 0 ; i < validator.getMsgsNumber() ; i++){
			Message msgItem = validator.getMsg(i);
			//Node
			if(msgItem.getElement() instanceof Node){
				String nodeId = "Note"+((Node)msgItem.getElement()).getPath();
				String nodeIdstr = nodeId.replaceAll("/", "\\\\");
				ValidateInfo validateInfo = new ValidateInfo(nodeIdstr,msgItem.toString(),msgItem.getSeverity().getFieldName());
				resultList.add(validateInfo);
			}
			else if(msgItem.getElement() instanceof Import   ||
					 msgItem.getElement() instanceof Include   ||
					 msgItem.getElement() instanceof Revision  ||
					 msgItem.getElement() instanceof Extension ||
					 msgItem.getElement() instanceof Feature   ||
					 msgItem.getElement() instanceof Typedef   ||
					 msgItem.getElement() instanceof YangUnknown 
					){
				String nodeId = "ModelElement@"+msgItem.getElement().getClass().getSimpleName()+"@"+msgItem.getElement().getName();
				ValidateInfo validateInfo = new ValidateInfo(nodeId,msgItem.toString(),msgItem.getSeverity().getFieldName());
				addResult(resultList,validateInfo);
			}else if(msgItem.getElement() instanceof Bit     ||
					 msgItem.getElement() instanceof Enum    ||
					 msgItem.getElement() instanceof Pattern ||
					 msgItem.getElement() instanceof Range   ||
					 msgItem.getElement() instanceof Type){
				
				ModelElement tempElement = getCurrNode(msgItem.getElement());
				if(tempElement instanceof Node){
					Node nodeItem = (Node)tempElement;
					String nodeId = "Note"+nodeItem.getPath();
					String nodeIdstr = nodeId.replaceAll("/", "\\\\");
					ValidateInfo validateInfo = new ValidateInfo(nodeIdstr,msgItem.toString(),msgItem.getSeverity().getFieldName());
					addResult(resultList,validateInfo);
				}else{
					String nodeId = "ModelElement@Typedef@"+msgItem.getElement().getName();
					ValidateInfo validateInfo = new ValidateInfo(nodeId,msgItem.toString(),msgItem.getSeverity().getFieldName());
					addResult(resultList,validateInfo);
				}
			}else if(msgItem.getElement() instanceof Module     ||
					 msgItem.getElement() instanceof BelongsTo   ){
				ValidateInfo validateInfo = new ValidateInfo("Module",msgItem.toString(),msgItem.getSeverity().getFieldName());
				addResult(resultList,validateInfo);
			}
		}
		
		
		return validateResult;
	}
	
	private void addResult(ArrayList<ValidateInfo> resultList , ValidateInfo validateInfo){
		Iterator<ValidateInfo> it = resultList.iterator();
		boolean isAdd = true;
		while(it.hasNext()){
			ValidateInfo tempInfo = it.next();
			if(tempInfo.nodeIdStr.equalsIgnoreCase(validateInfo.nodeIdStr)){
				tempInfo.reason += "###"+validateInfo.reason;
				isAdd = false;
				break;
			}
		}
		if(isAdd){
			resultList.add(validateInfo);
		}
	}
	
	private ModelElement getCurrNode(ModelElement element){	
		ModelElement tempElement = null;
		tempElement = element.getEnv().getParent();
		
		if(tempElement instanceof Node || tempElement instanceof Typedef){
			return tempElement;
		}else{
			tempElement = getCurrNode(tempElement);
		}
		
		
		return element;
	}
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public class ValidateInfo{
		private String nodeIdStr;
		private String reason;
		private String severity;
		
		public ValidateInfo(String nodeIdStr, String reason, String severity){
			this.nodeIdStr = nodeIdStr;
			this.reason    = reason;
			this.severity  = severity;
		}
		public String getNodeIdStr() {
			return nodeIdStr;
		}
		public void setNodeIdStr(String nodeIdStr) {
			this.nodeIdStr = nodeIdStr;
		}
		public String getReason() {
			return reason;
		}
		public void setReason(String reason) {
			this.reason = reason;
		}
		public String getSeverity() {
			return severity;
		}
		public void setSeverity(String severity) {
			this.severity = severity;
		}
	}
}
